-- =============================================
-- Author:		<Agurto, Jorge>
-- Modificado date: <24/10/2011>
-- Description:	<El Select del insert es un query Dinamico de Unions>
-- =============================================

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [GOOGLECODERS].[RolUpdate]
	@IdRol int = 0, 
	@Descripcion varchar(255) = null,
	@Habilitado bit = null,
	@QueryUnions varchar(2000) = null
AS
BEGIN
	BEGIN TRAN rolUpdate
	BEGIN TRY
		DECLARE @TableAux TABLE ( 
		IdFuncionalidad INT NOT NULL, 
		IdRol INT NOT NULL)

		UPDATE [GOOGLECODERS].[Roles]
		SET 
		Descripcion =	ISNULL(@Descripcion, Descripcion),
		Habilitado =	ISNULL(@Habilitado, Habilitado)
		WHERE IdRol = @IdRol

		if((@QueryUnions IS  NOT NULL))
		BEGIN
			DELETE FROM [GOOGLECODERS].[Funcionalidad_x_Rol]
			WHERE IdRol = @IdRol

			INSERT INTO @TableAux (IdFuncionalidad, IdRol ) 
			EXEC(@QueryUnions)

			INSERT INTO [GOOGLECODERS].[Funcionalidad_x_Rol]
			SELECT IdFuncionalidad, IdRol FROM @TableAux
		END

		COMMIT TRAN rolUpdate
		RETURN
	END TRY

	BEGIN CATCH
		ROLLBACK TRAN rolUpdate
		RETURN
	END CATCH
END